<script setup>
import { onMounted, ref } from 'vue'
import { useUserStore, useOrderStore } from '@/stores'
import { cancelOrderAPI } from '@/apis/order'
import { ElMessageBox, ElMessage } from 'element-plus'
import router from '@/router'
const userStore = useUserStore()
const orderStore = useOrderStore()
// tab列表
const tabTypes = [
  { name: 'all', label: '全部订单' },
  { name: 'unpay', label: '待付款' },
  { name: 'deliver', label: '待发货' },
  { name: 'receive', label: '待收货' },
  { name: 'complete', label: '已完成' },
  { name: 'cancel', label: '已取消' }
]
// 创建格式化函数
const fomartPayState = (payState) => {
  const stateMap = {
    1: '待付款',
    2: '待发货',
    3: '待收货',
    4: '已完成',
    5: '已取消'
  }
  return stateMap[payState]
}
// 订单列表
const params = ref({
  orderStatus: 0,
  userId: userStore.userInfo.data.userId,
  pageNum: 1,
  pageSize: 3
})
const getUserOrder = async () => {
  await orderStore.getOrderInfo(params)
  console.log(orderStore.orderInfo.length)
}
onMounted(() => getUserOrder())
// 导航栏切换
const tabChange = (type) => {
  params.value.orderStatus = type
  getUserOrder()
}

const cancelOrder = async (orderId) => {
  ElMessageBox.confirm('确定取消订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const order = {
        orderId: orderId,
        orderStatus: 5
      }

      await cancelOrderAPI(order)
      ElMessage.success('取消订单成功')
      getUserOrder()
    })
    .catch(() => {
      ElMessage.error('取消订单失败')
    })
}

const receive = async (orderId) => {
  ElMessageBox.confirm('确定点击收货吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const order = {
        orderId: orderId,
        orderStatus: 4
      }

      await cancelOrderAPI(order)
      ElMessage.success('收货成功')
      getUserOrder()
    })
    .catch(() => {
      ElMessage.error('收货失败')
    })
}

const toPay = (orderNumber) => {
  router.push({
    path: '/pay',
    query: {
      orderNumber: orderNumber
    }
  })
}
// 页面切换
const pageChange = (page) => {
  params.value.pageNum = page
  getUserOrder()
}
</script>

<template>
  <div class="order-container">
    <el-tabs @tab-change="tabChange">
      <!-- tab切换 -->
      <el-tab-pane
        v-for="item in tabTypes"
        :key="item.name"
        :label="item.label"
      />
      <div class="main-container">
        <div
          class="holder-container"
          v-if="
            orderStore.orderInfo === undefined ||
            orderStore.orderInfo.length === 0
          "
        >
          <el-empty description="暂无订单数据" />
        </div>
        <div v-else>
          <!-- 订单列表 -->
          <div
            class="order-item"
            v-for="order in orderStore.orderInfo"
            :key="order.orderId"
          >
            <div class="head">
              <span>下单时间：{{ order.orderTime }}</span>
              <span>订单编号：{{ order.orderNumber }}</span>
              <!-- 未付款，倒计时时间还有 -->
              <span class="down-time" v-if="order.orderStatus === 1">
                <i class="iconfont icon-down-time"></i>
                <b>付款截止: {{ order.orderTime }}</b>
              </span>
            </div>
            <div class="body">
              <div class="column goods">
                <ul>
                  <li v-for="item in order.details" :key="item.id">
                    <a class="image" href="javascript:;">
                      <img :src="item.productPicture" alt="" />
                    </a>
                    <div class="info">
                      <p class="name ellipsis-2">
                        {{ item.productName }}
                      </p>
                      <p class="attr ellipsis">
                        <span>{{ item.attrsText }}</span>
                      </p>
                    </div>
                    <div class="price">
                      ¥{{ item.productPrice?.toFixed(2) }}
                    </div>
                    <div class="count">x{{ item.productQuantity }}</div>
                  </li>
                </ul>
              </div>
              <div class="column state">
                <p>{{ fomartPayState(order.orderStatus) }}</p>
                <p v-if="order.orderStatus === 3">
                  <a href="javascript:;" class="green">查看物流</a>
                </p>
              </div>
              <div class="column amount">
                <p class="red">¥{{ order.totalPrice?.toFixed(2) }}</p>
                <p>（含运费：¥10）</p>
                <p>在线支付</p>
              </div>
              <div class="column action">
                <el-button
                  v-if="order.orderStatus === 1"
                  type="primary"
                  size="small"
                  @click="toPay(order.orderNumber)"
                >
                  立即付款
                </el-button>
                <el-button
                  v-if="order.orderStatus === 3"
                  type="primary"
                  size="small"
                  @click="receive(order.orderId)"
                >
                  确认收货
                </el-button>
                <!-- <p><a href="javascript:;">查看详情</a></p>
                <p v-if="[2, 3, 4, 5].includes(order.orderStatus)">
                  <a href="javascript:;">再次购买</a>
                </p> -->
                <p v-if="[4, 5].includes(order.orderStatus)">
                  <a href="javascript:;">申请售后</a>
                </p>
                <p v-if="order.orderStatus === 1">
                  <a @click="cancelOrder(order.orderId)">取消订单</a>
                </p>
              </div>
            </div>
          </div>
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              :total="orderStore.total"
              @current-change="pageChange"
              :page-size="params.pageSize"
              background
              layout="prev, pager, next"
            />
          </div>
        </div>
      </div>
    </el-tabs>
  </div>
</template>

<style scoped lang="scss">
.order-container {
  padding: 10px 20px;

  .pagination-container {
    display: flex;
    justify-content: center;
  }

  .main-container {
    min-height: 500px;

    .holder-container {
      min-height: 500px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

.order-item {
  margin-bottom: 20px;
  border: 1px solid #f5f5f5;

  .head {
    height: 50px;
    line-height: 50px;
    background: #f5f5f5;
    padding: 0 20px;
    overflow: hidden;

    span {
      margin-right: 20px;

      &.down-time {
        margin-right: 0;
        float: right;

        i {
          vertical-align: middle;
          margin-right: 3px;
        }

        b {
          vertical-align: middle;
          font-weight: normal;
        }
      }
    }

    .del {
      margin-right: 0;
      float: right;
      color: #999;
    }
  }

  .body {
    display: flex;
    align-items: stretch;

    .column {
      border-left: 1px solid #f5f5f5;
      text-align: center;
      padding: 20px;

      > p {
        padding-top: 10px;
      }

      &:first-child {
        border-left: none;
      }

      &.goods {
        flex: 1;
        padding: 0;
        align-self: center;

        ul {
          li {
            border-bottom: 1px solid #f5f5f5;
            padding: 10px;
            display: flex;

            &:last-child {
              border-bottom: none;
            }

            .image {
              width: 70px;
              height: 70px;
              border: 1px solid #f5f5f5;
            }

            .info {
              width: 220px;
              text-align: left;
              padding: 0 10px;

              p {
                margin-bottom: 5px;

                &.name {
                  height: 38px;
                }

                &.attr {
                  color: #999;
                  font-size: 12px;

                  span {
                    margin-right: 5px;
                  }
                }
              }
            }

            .price {
              width: 100px;
            }

            .count {
              width: 80px;
            }
          }
        }
      }

      &.state {
        width: 120px;

        .green {
          color: $xtxColor;
        }
      }

      &.amount {
        width: 200px;

        .red {
          color: $priceColor;
        }
      }

      &.action {
        width: 140px;

        a {
          display: block;

          &:hover {
            color: $xtxColor;
          }
        }
      }
    }
  }
}
</style>
